package org.midy.infrastructure;

import org.midy.infrastructure.customer.OnlineList;
import org.midy.infrastructure.tools.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class ConsoleInputThread implements Runnable{
    private SocketChannel server;

    private IOEventDrivenContainer ioEventDrivenContainer;

    public ConsoleInputThread() {
    }

    public ConsoleInputThread(SocketChannel server) {
        this.server = server;
    }

    public ConsoleInputThread(SocketChannel server, IOEventDrivenContainer ioEventDrivenContainer) {
        this.server = server;
        this.ioEventDrivenContainer = ioEventDrivenContainer;
    }

    public static Thread startConsoleInputThread(SocketChannel socketChannel, IOEventDrivenContainer ioEventDrivenContainer){
        Thread thread = new Thread(new ConsoleInputThread(socketChannel, ioEventDrivenContainer), "console-dome-thread");
        thread.setDaemon(true);
        thread.start();
        return thread;
    }

    @Override
    public void run() {
        boolean exit = false;
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
            OnlineList.UserLogin userLogin = null;
            while (!exit) {
                String readLineConsole = bufferedReader.readLine();
                if(userLogin == null) {
                    userLogin = OnlineList.query(this.server);
                }
                OnlineList.sendMessage(userLogin.getAcct(), readLineConsole.getBytes(StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            Logger.info("控制台输入流出现异常");
        }
        Logger.info(" exit console input ");
    }
}
